﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Monitor.Core.Sensor
{
    class KafkaClusterSensor : ICompositeSensor
    {
        private List<ISensor> _sensors;
        private ServiceStatus _status;
        private int _id;
        public KafkaClusterSensor(int id)
        {
            _id = id;
            _sensors = new List<ISensor>();
        }

        public void AddComponent(ISensor sensor)
        {
            this.AddComponent(sensor as KafkaSensor);
        }
        public void AddComponent(KafkaSensor sensor)
        {
            _sensors.Add(sensor);
        }

        public int Id
        {
            get { return _id; }
        }

        private string _description;
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }

        public ServiceStatus Status
        {
            get { return _status; }
        }

        public ServiceStatus Ping()
        {
            _lastRefreshTime = DateTime.Now;

            Parallel.ForEach<ISensor>(_sensors, (s) =>
            {
                s.Ping();
            });

            int alive = _sensors.Count(s => s.Status == ServiceStatus.Alive);
            if (alive == _sensors.Count())
            {
                _status = ServiceStatus.Alive;
                return _status;
            }
            if (alive >= 1)
            {
                _status = ServiceStatus.Unstable;
                return _status;
            }
            else
            {
                _status = ServiceStatus.Dead;
                return _status;
            }
        }

        private DateTime _lastRefreshTime;
        public DateTime LastRefreshTime
        {
            get { return _lastRefreshTime; }
        }

        private int _interval;
        public int Interval
        {
            get { return _interval; }
            set { _interval = value; }
        }

        public string LastError
        {
            get
            {
                StringBuilder str = new StringBuilder();
                foreach (var s in _sensors)
                {
                    if (s.Status != ServiceStatus.Alive)
                    {
                        str.Append(s.Description + ": " + s.LastError + '\n');
                    }
                }
                return str.ToString();
            }
        }
    }
}
